package es.cazadoresmadridejos.beans.controller.male;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import es.cazadoresmadridejos.beans.manager.male.MaleManager;
import es.cazadoresmadridejos.beans.validator.male.MaleValidator;
import es.cazadoresmadridejos.model.Male;
import es.cazadoresmadridejos.propertyeditor.MalePropertyEditor;
import es.cazadoresmadridejos.util.validation.ValidationContainer;


@Controller
public class MaleCreateModifyController {

	@Autowired private MaleManager maleManager;
	@Autowired private MaleValidator maleValidator;
	@Autowired private MessageSource messageSource;
	
	@InitBinder
	public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Throwable{
		binder.registerCustomEditor(Male.class, new MalePropertyEditor(maleManager));
	}
	
	@RequestMapping(value="/maleCreateModify.html",method=RequestMethod.GET)
	public ModelAndView createModify(
			@RequestParam(value="id",required=false) Male male) throws Throwable {
		ModelAndView mv = new ModelAndView();
		if(male == null){
			male = new Male();
		}
		mv.addObject("male",male);
		
		return mv;
	}
	@RequestMapping(value="/maleCreateModify.html",method=RequestMethod.POST)
	public ModelAndView submit(
			@ModelAttribute("male") Male male, 
			BindingResult result, 
			SessionStatus status,
			HttpServletRequest request
			) throws Throwable {
		
		ModelAndView mv = new ModelAndView("index");
		List<ValidationContainer> errors = maleValidator.validate(male);
		if(errors.isEmpty()){
			String message = messageSource.getMessage("${successMessage}",null, "${successMessage}", request.getLocale());
			mv.addObject("okMessage", message);
		}else{
			mv.addObject("errors",errors);
		}
		
		return mv;
	}
}
